import jwt
import time
from tornado import gen
from base.BaseHandler import BaseHandler, AuthHandler
from base.DateHandler import DateHandler
from base.Models import Users, UserDoLog
from config import config


class Login(BaseHandler):
    @gen.coroutine
    def post(self):
        result = self.result()
        try:
            data = self.get_body()
            email = self.data_not_null(data, "email", "请输入邮箱！")
            password = self.data_not_null(data, "password", "请输入密码！")

            user = self.session.query(Users).filter_by(email=email, password=password, is_delete=0).first()
            if not user:
                self.data_except("邮箱或密码不正确！")
            print(user.nick_name)
            token = {
                "user_id": user.id,
                "user_name": user.nick_name,
                "login_time": DateHandler.now()
            }
            token = jwt.encode(token, config["user_key"], algorithm="HS256")
            user.last_login_time = DateHandler.now()
            self.record_user_operation(user.id, user.nick_name, todo="用户登录。")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "登录成功！"
            result["data"] = {
                "token": str(token, encoding="utf-8"),
                "user_name": user.nick_name,
                "user_head_img": user.head_img
            }
            self.logger.info(f"用户 {user.nick_name} 登录 ")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, "登录失败！")
        self.write(result)


class LogOut(AuthHandler):
    @gen.coroutine
    def post(self):
        result = self.result()
        try:
            self.record_user_operation(self.user_id, self.user_name, todo="用户退出。")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "退出成功！"
            self.logger.info(f"用户 {self.user_name} 退出。")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, "退出失败！")
        self.write(result)
